package com.xxjh.brs.mvc.filter;

import com.xxjh.brs.ftp.common.api.dto.LoginUserInfo;
import com.xxjh.brs.ftp.common.api.enums.ResponseStatus;
import com.xxjh.brs.ftp.common.encryption.TokenParseUtil;
import com.xxjh.brs.ftp.common.exceptions.ConditionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.xxjh.brs.ftp.common.encryption.EncryptionConstants.AUTHORIZATION;

/**
 * @author CHENCHEN
 * @title 用户拦截器
 * @company 新兴际华科技（天津）有限公司
 * @create 2024-07-03 19:21
 */
@Slf4j
@Component
public class LoginUserInfoInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 部分请求不需要带有身份信息, 即白名单
        if (checkWhiteListUrl(request.getRequestURI())) {
            return true;
        }
        String token = request.getHeader(AUTHORIZATION);
        if(StringUtils.isEmpty(token)){
            throw new ConditionException(ResponseStatus.UNAUTHORIZED);
        }
        LoginUserInfo loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
        AccessContext.setThreadLocal(loginUserInfo);
        return true;
    }

    /**
     * 后置拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * preHandle返回true，DispatcherServlet进行视图的渲染之后，多用于清理资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(AccessContext.getThreadLocal() != null) AccessContext.clearLoginUserInfo();
    }

    /**
     * 校验是否是白名单接口
     * @param url
     * @return
     */
    private boolean checkWhiteListUrl(String url){
        return StringUtils.containsAny(
                url,
                "swagger-ui"
        );
    }
}
